package cn.yeyiu.netonlinevideo.util;


import android.util.Log;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.parser.Parser;

public class ParserFactory {
    private static List<SourceData> mSources;
    private static Map<String, Parser> parserMap;

    public static void initSources(List<SourceData> sources){
        mSources = sources;
    }

    private static void initParsers() {
        parserMap = new HashMap<>();
        for (SourceData source : mSources) {
            try {
                Parser parser = (Parser) Class.forName("cn.yeyiu.netonlinevideo.parser."
                        + source.type + "." + source.parser
                ).getConstructor(SourceData.class).newInstance(source);

                parserMap.put(source.code, parser);
            }catch (Exception e) {
                Log.d("Parser", "initParsersFail: "+source.code+", "+source.type+","+source.parser);
                e.printStackTrace();
            }
        }
    }

    public static Parser getParser(String code) {
        if (parserMap == null) {
            initParsers();
        }
        return parserMap.get(code);
    }

    public static SourceData getSource(int index){
        return mSources.get(index);
    }

    public static int getSourcesCount(){
        return mSources.size();
    }
}
